package popoer.price.thief.service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.logging.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.zip.GZIPInputStream;

import org.apache.commons.lang.StringUtils;

public abstract class BaseThief {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(BaseThief.class
			.getName());

	public BaseThief() {
		super();
	}

	protected String getContent(String relativeURL)
			throws MalformedURLException, UnsupportedEncodingException,
			IOException {
		return getContent(relativeURL, new HashMap<String, String>(), null);
	}

	protected String getContent(String relativeURL,
			Map<String, String> cookies, String referer)
			throws MalformedURLException, UnsupportedEncodingException,
			IOException {
		URL url = getURL(relativeURL);
		if (logger.isLoggable(Level.FINE)) {
			logger.fine("String - URL url=" + url); //$NON-NLS-1$
		}
		String cookiesStr = "";
		Set<Entry<String, String>> entrySet = cookies.entrySet();
		for (Entry<String, String> entry : entrySet) {
			String key = entry.getKey().trim();
			if (key.equals("path") || key.equals("domain")
					|| key.equals("expires")) {
				continue;
			}
			cookiesStr += entry.getKey() + "=" + entry.getValue() + ";";
		}
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
		conn
				.setRequestProperty(
						"User-Agent",
						"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; QQDownload 627; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
		conn.setRequestProperty("Cookie", cookiesStr);
		conn
				.setRequestProperty("Accept",
						"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		conn
				.setRequestProperty("Accept-Language",
						"zh-cn,en-us;q=0.7,zh;q=0.3");
		conn.setRequestProperty("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
		conn.setRequestProperty("Keep-Alive", "115");
		conn.setRequestProperty("Connection", "keep-alive");
		if (StringUtils.isNotEmpty(referer)) {
			conn.setRequestProperty("Referer", referer);
		}
		conn.setRequestMethod("GET");

		String responseEncoding = conn.getHeaderField("Content-Encoding");
		InputStream in;
		if ("gzip".equals(responseEncoding)) {
			in = new GZIPInputStream(conn.getInputStream());
		} else {
			in = conn.getInputStream();
		}

		BufferedReader reader = new BufferedReader(new InputStreamReader(in,
				getEncoding()));
		StringBuffer html = new StringBuffer(1024);
		String line;
		while ((line = reader.readLine()) != null) {
			html.append(line + "\n");
		}
		String headerName = null;
		for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
			if (headerName.equalsIgnoreCase("Set-Cookie")) {
				cookiesStr = conn.getHeaderField(i);
				String[] cookieStr = cookiesStr.split(";");
				for (String cookie : cookieStr) {
					String[] cookieAry = cookie.split("=");
					cookies.put(cookieAry[0], cookieAry[1]);
				}
			}
		}
		reader.close();
		String result = html.toString();
		if (logger.isLoggable(Level.FINER)) {
			logger.finer("String - String result=" + result); //$NON-NLS-1$
		}
		return result;
	}

	protected URL getURL(String relativeURL) throws MalformedURLException {
		return new URL(this.getBaseURL() + relativeURL);
	}

	public abstract String getBaseURL();

	public abstract String getEncoding();

}